package org.langqiao.network.socket;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class ChatUDPJFrame extends JFrame implements ActionListener{
	private String name;//网名
	private InetAddress destip;//目标主机名或IP地址
	private int destport;//目标主机的端口号
	private JTextArea text_receiver;//显示对话框内容的的文本区
	private JTextField text_sender;//输入发送内容的文本行
	public ChatUDPJFrame(String name,String host,int destport,int receiveport)throws IOException
	{
		super("聊天室	"+name+" "+InetAddress.getLocalHost()+":"+receiveport);
		this.setBounds(320,240,360,240);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.text_receiver=new JTextArea();
		this.text_receiver.setEditable(false);//不可编辑
		this.getContentPane().add(new JScrollPane(this.text_receiver));
		
		JPanel panel=new JPanel();
		this.getContentPane().add(panel,"South");
		this.text_sender=new JTextField(20);
		panel.add(text_sender);
		JButton button_send=new JButton();
		panel.add(button_send);
		button_send.addActionListener(this);
		this.setVisible(true);
		
		this.name=name;
		this.destip=InetAddress.getByName(host);
		this.destport=destport;
		byte data[]=new byte[512];//一下接收数据包并显示
		DatagramPacket pack=new DatagramPacket(data,data.length);//创建待接收数据包
		DatagramSocket socket=new DatagramSocket(receiveport);//创建待接收的Socket
		while(socket!=null)
		{
			socket.receive(pack);//接收数据报包
			int length=pack.getLength();//获得包长度
			String message=new String(pack.getData(),0,length);//获得包中字节数据并转成字符窜
			text_receiver.append(message+"\n");
			
		}
	}
	public void actionPerformed(ActionEvent e)
	{
		if(e.getActionCommand()=="发送")
		{
			byte buffer[]=(name+"说:"+text_sender.getText()).getBytes();//将字符窜转换为字节
			try
			{
				DatagramPacket pack=new DatagramPacket(buffer,buffer.length,destip,destport);
				new DatagramSocket().send(pack);
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
				
			}
			text_receiver.append("我说："+text_sender.getText()+"\n");
			text_sender.getText();
		}
	}
	public static void main(String [] args)throws Exception
	{
		new ChatUDPJFrame("玉公主","202.119.161.101",3002,3001);
		
	}

}
